package util;

import java.io.File;
import java.net.URL;
import java.net.URLDecoder;

public class FileUtils {

	public static boolean checkDir(File dir){
		  return dir.exists()&&dir.isDirectory();
	}
	
	  public static String getAppPath(Class cls)
	    {
	        if(cls == null)
	            throw new IllegalArgumentException("\u53C2\u6570\u4E0D\u80FD\u4E3A\u7A7A\uFF01");
	        ClassLoader loader = cls.getClassLoader();
	        String clsName = (new StringBuilder(String.valueOf(cls.getName()))).append(".class").toString();
	        Package pack = cls.getPackage();
	        String path = "";
	        if(pack != null)
	        {
	            String packName = pack.getName();
	            if(packName.startsWith("java.") || packName.startsWith("javax."))
	                throw new IllegalArgumentException("\u4E0D\u8981\u4F20\u9001\u7CFB\u7EDF\u7C7B\uFF01");
	            clsName = clsName.substring(packName.length() + 1);
	            if(!packName.contains("."))
	            {
	                path = (new StringBuilder(String.valueOf(packName))).append("/").toString();
	            } else
	            {
	                int start = 0;
	                int end = 0;
	                for(end = packName.indexOf("."); end != -1; end = packName.indexOf(".", start))
	                {
	                    path = (new StringBuilder(String.valueOf(path))).append(packName.substring(start, end)).append("/").toString();
	                    start = end + 1;
	                }

	                path = (new StringBuilder(String.valueOf(path))).append(packName.substring(start)).append("/").toString();
	            }
	        }
	        URL url = loader.getResource((new StringBuilder(String.valueOf(path))).append(clsName).toString());
	        String realPath = url.getPath();
	        int pos = realPath.indexOf("file:");
	        if(pos > -1)
	            realPath = realPath.substring(pos + 5);
	        pos = realPath.indexOf((new StringBuilder(String.valueOf(path))).append(clsName).toString());
	        realPath = realPath.substring(0, pos - 1);
	        if(realPath.endsWith("!"))
	            realPath = realPath.substring(0, realPath.lastIndexOf("/"));
	        try
	        {
	            realPath = URLDecoder.decode(realPath, "utf-8");
	        }
	        catch(Exception e)
	        {
	            throw new RuntimeException(e);
	        }
	        return realPath;
	    }
}
